<?php

namespace backend\controllers;

use Yii;
use backend\models\Config;
use backend\base\BaseBackendController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * CityController implements the CRUD actions for City model.
 */
class ConfigController extends BaseBackendController
{
	public $layout= false;
  
	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    
	//更新文件缓存
    public function updateCache(){
		$cache = array();
		$sql="SELECT * FROM {{%config}}";
		$data = Yii::$app->db->createCommand($sql)->queryAll();
		foreach($data as $v){
			$cache[$v['key']] = $v['val'];
		}
		Yii::$app->FileCache->set('config', $cache);
	}


	public function actionIndex()
	{       
		$model = new Config();
		if(isset($_POST['Config']))
		{
			foreach($_POST['Config'] as $k=>$v){
				$sql = "replace into {{%config}}(`key`, `val`) values(:key, :val);";
                $conn=Yii::$app->db->createCommand($sql);
                $conn->bindValue(':key',$k);
                $conn->bindValue(':val',$v);
			    $result=$conn->execute();
			}
            $this->updateCache();
			$this->OperTips('/config/index');
		}
        $sql = "SELECT * FROM {{%config}}";
		$rows = Yii::$app->db->createCommand($sql)->queryAll();
		$data = array();
		foreach($rows as $k=>$v){
			$data[$v['key']] = $v['val'];
		}
		return $this->render('config',array(
			'model'=>$model,
			'rows'=>$data,
		));
	}


}
